/**
 *
 * Copyright 2015-present reading
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

import getUrl from './UrlUtil';
import { UA } from './AttachParamsUtil';
import store from 'react-native-simple-store'
import { getSignatureDataFromStore, getEncryptedToken } from './TokenUtil';
const AESData = require('../data/AE01.json');
import { SCRM_API } from '../constants/Urls';

const request = (url, method, body) => {
  let isOk;

  return new Promise((resolve, reject) => {
    fetch(getUrl(url), {
      method,
      // mode: "cors",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset=utf-8',
        'x-requested-with': 'XMLHttpRequest',
        // 'host': getHost(url),
        // 'origin': getHost(url)
      },
      body
    })
      .then((response) => {
        // console.log(response, 'fuck')
        if (response.ok) {
          isOk = true;
        } else {
          isOk = false;
        }
        return response.json();
      })
      .then((responseData) => {
        // console.log(responseData, body, 'fuck')
        if (typeof responseData.errcode !== 'undefined' && responseData.errcode === 10003) {
          store.get('token')
            .then(token => {
              if (url.indexOf(token) > -1) {
                refreshToken()
                  .then(freshToken => {
                    const freshUrl = url.replace(token, freshToken);
                    resolve(request(freshUrl, method, body))
                    store.save('token', freshToken)
                  })
              }
            })
        } else {
          if (isOk) {
            resolve(responseData);
          } else {
            reject(responseData);
          }
        }
        
      })
      .catch((error) => { 
        reject(error);
      });
  });
};

const refreshToken = () => {
  const {key, iv} = AESData;
  return getSignatureDataFromStore('authData', key, iv)
    .then((signatureData) => {
      const {site_id, uim, suid, timeStamp, signature} = signatureData;
      return requestRefreshToken(site_id, uim, suid, timeStamp, signature);
    }).then((freshTokenData) => getEncryptedToken(freshTokenData.results, key, iv))
}

const requestRefreshToken = (site_id, uim, suid, timeStamp, signature) => {
  console.log('requestRefreshToken fuck', site_id, uim, suid, timeStamp, signature)
  return request(`${SCRM_API}/login`, 'post', UA({
    site_id: site_id,
    encrypted_type: 1,
    uim: uim,
    suid: suid,
    timestamp: timeStamp,
    signature: signature
  }))
}

const getHost = (url) => {
  return url.replace(/^((\w+:)?\/\/[^\/]+\/?).*$/,'$1');
}

export default {
  request
};
